package models

import (
	"strings"
	"t11Lib/t11Errors"
	"t11Lib/t11Model"
	"time"
)

type WxUser struct {
	//Id为appId-openId
	t11Model.BaseMdl `json:"-"` //不对外透露openId
	Subscribe        int       `json:"subscribe" orm:"null"`
	Nickname         string    `json:"nickname" orm:"null"`
	Sex              int       `orm:"null"`
	Language         string    `orm:"null"`
	City             string    `orm:"null"`
	Province         string    `orm:"null"`
	Country          string    `orm:"null"`
	HeadImgUrl       string    `json:"headimgurl" orm:"null"`
	SubscribeTime    time.Time `orm:"null"`
	UnionId          string    `json:"unionid" orm:"null"`
	Remark           string    `orm:"null"`
	GroupId          int       `json:"groupid" orm:"null"`
}

func (self *WxUser) SetId(appId, openId string) {
	self.Id =  openId
}

type wxUserDao struct{}

var WxUserDao wxUserDao

func (self wxUserDao) GetByOpenId(conn *t11Model.DbConn, appId, openId string) (*WxUser, t11Errors.T11Error) {
	u := &WxUser{}
	u.SetId(appId, openId)
	e := conn.Read(u)
	return u, t11Errors.Wrap(e)
}

func (self wxUserDao) SaveWxUser(conn *t11Model.DbConn, wxUser *WxUser) t11Errors.T11Error {
	_, e := conn.Insert(wxUser)
	return t11Errors.Wrap(e)
}

type JwtToken struct {
	AppType string
	AppId   string
	UserId  string
	idStr   string
}

func (self *JwtToken) ToId() string {
	if self.idStr != "" {
		return self.idStr
	}
	return self.AppType + "-" + self.AppId + "-" + self.UserId
}
func ParseJwtToken(tkStr string) *JwtToken {
	items := strings.Split(tkStr, "-")
	if len(items) < 3 {
		return nil
	}
	ret := &JwtToken{}
	ret.AppType = items[0]
	ret.AppId = items[1]
	ret.UserId = strings.Join(items[2:], "-")
	return ret
}
